package com.wonders.xianningsocialinsurance.fragments;


import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.wang.avi.AVLoadingIndicatorView;
import com.wonders.xianningsocialinsurance.App;
import com.wonders.xianningsocialinsurance.R;
import com.wonders.xianningsocialinsurance.adapters.PoiSearchResultAdapter;
import com.wonders.xianningsocialinsurance.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;


public class NearbyFragment extends Fragment implements RadioGroup.OnCheckedChangeListener{
    private static final String TAG = "NearbyFragment";
    View rootView;
    RadioGroup seatch_rdGroup;
    RecyclerView recyclerView;
    TextView current_location_tv;
    PoiSearch poiSearch;
    int pageNum = 0;
    String keyword = "社会保险";
    LatLng location_latlng;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private List<PoiInfo> infos = new ArrayList<PoiInfo>();
    PoiSearchResultAdapter poiSearchResultAdapter;
    String location_name = null;
    LinearLayoutManager layoutManager;
    AVLoadingIndicatorView avloadingIndicatorView;
    int result_num = 0;
    //    SwipeRefreshLayout refreshLayout;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocationClient = new LocationClient(getActivity().getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );    //注册监听函数
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_nearby, container, false);
        initView();
        return rootView;
    }
    void initView(){
        seatch_rdGroup = (RadioGroup)rootView.findViewById(R.id.nearby_search);
        seatch_rdGroup.setOnCheckedChangeListener(this);
        current_location_tv = (TextView) rootView.findViewById(R.id.current_location_tv) ;
        if (StringUtils.hasText(location_name))
            current_location_tv.setText(location_name);
        else
            current_location_tv.setText("正在定位...");
        initLocation();

        avloadingIndicatorView = (AVLoadingIndicatorView)rootView.findViewById(R.id.avloadingIndicatorView);
        poiSearch = PoiSearch.newInstance();
        poiSearchResultAdapter = new PoiSearchResultAdapter(getActivity(),infos);
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView = (RecyclerView)rootView.findViewById(R.id.recycler_view);
        recyclerView.setNestedScrollingEnabled(true);
//        recyclerView.setItemAnimator(new SlideInUpAnimator(new OvershootInterpolator(1f)));
//        recyclerView.getItemAnimator().setAddDuration(1000);
//        recyclerView.getItemAnimator().setRemoveDuration(1000);
//        recyclerView.getItemAnimator().setMoveDuration(1000);
//        recyclerView.getItemAnimator().setChangeDuration(1000);
        recyclerView.setAdapter(poiSearchResultAdapter);
        recyclerView.setLayoutManager(layoutManager);


        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = getResources().getDimensionPixelSize(R.dimen.recycler_dimens);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.recycler_dimens);
            }

        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition == poiSearchResultAdapter.getItemCount()-1) {
                    setUpPoiSearch();
                }
            }
        });


    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.rd1:
                keyword = "社会保险";
                break;
            case R.id.rd2:
                keyword = "药店";
                break;
            case R.id.rd3:
                keyword = "医院";
                break;
            case R.id.rd4:
                keyword = "银行";
                break;
            default:
                break;
        }
        pageNum=0;
        infos.clear();
        setUpPoiSearch();

    }
    void setUpPoiSearch(){
        avloadingIndicatorView.setVisibility(View.VISIBLE);
        poiSearch.searchNearby(new PoiNearbySearchOption().keyword(keyword)
                .location(location_latlng).radius(1000)
                .sortType(PoiSortType.distance_from_near_to_far)
                .pageCapacity(10)
                .pageNum(pageNum));
        poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    result_num = poiResult.getTotalPoiNum();
                    infos.addAll(poiResult.getAllPoi());
                    poiSearchResultAdapter.notifyDataSetChanged();
//                    for (PoiInfo info:infos)
//                        Log.e(TAG,"Noerror"+info.name);
                    if (pageNum<poiResult.getTotalPageNum())
                        pageNum++;
                    avloadingIndicatorView.setVisibility(View.GONE);

                }
                if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                    avloadingIndicatorView.setVisibility(View.GONE);
                    return;
                }
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
                if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    //详情检索失败
                    // result.error请参考SearchResult.ERRORNO
                }
                else {
                    //检索成功
                }
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        });

    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            location_name = location.getAddrStr();
            current_location_tv.setText(location_name);
            location_latlng = new LatLng(location.getLatitude(),location.getLongitude());
            App.location_latlng = location_latlng;
            setUpPoiSearch();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        poiSearch.destroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
